package com.meixiang.adapter.shopping;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.meixiang.R;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 搜索历史列表适配器
 *
 * @author LZRUI
 */
public class SearchHistoryAdapter extends BaseAdapter {

    private List<String> historyKeys;

    /**
     * 刷新列表
     *
     * @param keys
     */
    public void refreshList(List<String> keys) {
        if (keys != null && !keys.isEmpty()) {
            historyKeys = keys;
            notifyDataSetChanged();
        }
    }

    /**
     * 清空列表
     */
    public void clearList() {
        if (historyKeys.size() > 0) {
            historyKeys = null;
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        return historyKeys == null ? 0 : historyKeys.size();
    }

    @Override
    public Object getItem(int position) {
        return historyKeys.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_search_history, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.tvKey.setText(historyKeys.get(position) == null ? "" : historyKeys.get(position));
        return convertView;
    }

    static class ViewHolder {
        @Bind(R.id.tv_key)
        TextView tvKey;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
